const {
  paramsFormat
} = require('@/common/paramsFormat');
const {
  showLoading,
  hideLoading,
} = require('@/common/common');
import qs from '@/lib/qs'
const urlMap = {
  develop3: { // 开发t3
    url: 'https://t3.fsyuncai.com',
    ycMainUrl: 'https://t3.fsyuncai.com',
    ycUrl: 'https://t3.fsyuncai.com/api/mobile',
    comUrl: 'https://t3.fsyuncai.com',
    webUrl: 'https://t3.fsyuncai.com',
    tdkUrl: 'https://m2-t3.xfs.com',
  },
  develop: { // 开发
    url: 'https://t4.fsyuncai.com',
    ycMainUrl: 'https://t4.fsyuncai.com',
    ycUrl: 'https://t4.fsyuncai.com/api/mobile',
    comUrl: 'https://t4.fsyuncai.com',
    webUrl: 'https://t4.fsyuncai.com',
    tdkUrl: 'https://m2-t4.xfs.com',
  },
  trial: { //仿真
    url: 'https://storeapplet.pre.xinfangsheng.com', //小程序仿真环境
    ycMainUrl: 'https://pre.fsyuncai.com', //云采仿真环境
    ycUrl: 'https://pre.fsyuncai.com/api/mobile', //云采仿真环境
    comUrl: 'https://commuapi.pre.xinfangsheng.com', //基础资料pre https://commuapi.pre.xinfangsheng.com
    webUrl: 'https://pre.fsyuncai.com',
    tdkUrl: 'https://m2-pre.xfs.com',
  },
  release: { //生产
    url: 'https://storeapplet.xinfangsheng.com', //小程序正式环境
    ycMainUrl: 'https://ycapi.xfs.com', //云采正式环境主域名
    ycUrl: 'https://ycapi.xfs.com/api/mobile', //云采正式环境
    comUrl: 'https://commuapi.fsyuncai.com', //基础资料生产
    webUrl: 'https://www.xfs.com',
    tdkUrl: 'https://m.xfs.com',
  }
}
const envVersion = 'release'
uni.$u.vuex('vuex_baseURL', urlMap[envVersion]);
uni.$u.vuex('vuex_envVersion', envVersion);
module.exports = (vm) => {
  uni.$u.http.setConfig((config) => {
    // #ifdef MP-WEIXIN
    // config.custom.envUrlObj = urlMap[wx.getAccountInfoSync().miniProgram.envVersion]
    // #endif
    // #ifdef MP-ALIPAY
    // config.custom.envUrlObj = urlMap[envVersion]
    // #endif
    config.custom.envUrlObj = urlMap[envVersion]
    config.originalData = true; /* 是否在拦截器中返回服务端的原始数据 */
    return config
  })
  // 请求拦截
  uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
    // 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
    if (!config.custom.hideLoadingFlag) {
      showLoading()
    }
    config.baseURL = config.custom.envUrlObj[config.custom.type];
    config.data = config.data || {}
    /*签名公共参数设置*/
    const lifeData = uni.getStorageSync('lifeData')
    const vuex_accountInfo = lifeData.vuex_accountInfo ? lifeData.vuex_accountInfo : {}
    const vuex_memberInfo = lifeData.vuex_memberInfo ? lifeData.vuex_memberInfo : {}
    const vuex_crmCustomerInfos = lifeData.vuex_crmCustomerInfos && lifeData.vuex_crmCustomerInfos.length > 0 ? lifeData.vuex_crmCustomerInfos[0] : {}

    const {
      loginAccount,
      mobilePhone,
      unionid, //微信关联标识
      memberId,
      openid, //小程序关联标识openId
      userId, //小程序关联标识openId
    } = vuex_accountInfo
    const {
      accountType = 20,
      platformType,
    } = vuex_memberInfo
    const {
      customerCode,
      customerId,
    } = vuex_crmCustomerInfos
    const {
      brand, //设备品牌
      system, //操作系统名称及版本
      SDKVersion, //客户端基础库版本
      version, //引擎版本号
      model, //设备型号
      deviceId, //设备 id
    } = (lifeData.vuex_systemInfo && lifeData.vuex_systemInfo[1]) || {}
    const addParams = {
      member_id: memberId,
      account_type: accountType,
      customerCode: customerCode || '',
      customerId: customerId || '',
      token: lifeData.vuex_token || '',
      timestamp: new Date().getTime(),
      platformName: platformType || ''
    }
    if (customerCode && customerId) {
      addParams.customer_id = customerId
      addParams.customer_code = customerCode
    } else {
      addParams.customer_id = '';
      addParams.customer_code = '';
    }
    if (config.method != 'GET') {
      const commonData = {
        loginAccount: loginAccount,
        login_account: loginAccount,
        mobilePhone: mobilePhone,
        unionId: unionid,
        memberId: memberId,
        openId: openid,
        userId: config.data.userId ? config.data.userId : userId,
        vuex_loginStatus: lifeData.vuex_loginStatus, //登录状态
      }
      const feedbackcommonData = {
        loginAccount: loginAccount,
        login_account: loginAccount,
        unionId: unionid,
        memberId: memberId,
        openId: openid,
        userId: config.data.userId ? config.data.userId : userId,
        vuex_loginStatus: lifeData.vuex_loginStatus, //登录状态
      }
      const systemData = {
        versions: '1.0.1', //小程序版本号
        network: lifeData.vuex_networkType,
        wxVersions: version, //
        deviceBrand: brand,
        osVersion: system,
        sdkVersion: SDKVersion,
        deviceType: model, //设备型号
        deviceId: deviceId, //设备id
        // 云采系统
        device_brand: brand, //公共参数：移动端设备品牌
        device_id: deviceId, //设备号
      }
      const systemDataX = {
        device_platform: lifeData.vuex_provider + 'mini',
      }
      const systemDataM = {
        device_platform: 'h5'
      }
      if (config.url.indexOf('tokenByCodeForAli') == -1 && config.url.indexOf('loginServiceV3') == -1) {
        config.data = { ...config.data, ...commonData }
      }
      if (config.url.indexOf('searchFrontFreeBackList') != -1) { //意见反馈查询列表 入参不需要手机号
        delete config.data.mobilePhone;
        config.data = { ...config.data, ...feedbackcommonData }
      }
      // #ifdef MP-ALIPAY || MP-WEIXIN
      config.data = { ...config.data, ...systemData, ...systemDataX }
      // #endif
      //#ifdef H5
      config.data = { ...config.data, ...systemData, ...systemDataM }
      // #endif
      if (Object.keys(config.data).indexOf('sign') == -1 && config.url.indexOf('tokenByCodeForAli') == -1 && config.url.indexOf('getMobileVerifyCode') == -1 && config.url.indexOf('setMemberNewPwd') == -1) {
        config.data = paramsFormat(config.data, addParams, config.url)
      }
    }
    if (config.url) {
      if (config.header['Content-Type'] && config.header['Content-Type'] == 'application/x-www-form-urlencoded') {
        config.data = qs.stringify(config.data);
      }
    }
    return config
  }, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
  })

  // 响应拦截
  uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
    // 自定义参数
    hideLoading()
    const custom = response.config?.custom
    if (response.statusCode !== 200) {
      // 如果没有显式定义custom的toast参数为false的话，默认对报错进行toast弹出提示
      if (custom.toast !== false) {
        uni.$u.toast(response.message)
      }

      // 如果需要catch返回，则进行reject
      if (custom?.catch) {
        return Promise.reject(response)
      } else {
        // 否则返回一个pending中的promise，请求不会进入catch中
        return new Promise(() => { })
      }
    }
    return response.data === undefined ? {} : response.data
  }, (response) => {
    // 对响应错误做点什么 （statusCode !== 200）
    hideLoading()
    uni.getNetworkType({
      success: function(res) {
        if (res.networkType == 'none') {
          response.errMsg = '信号可能跑到外星球了哦～'
          return Promise.reject(response)
        }
      }
    });
    return Promise.reject(response)
  })
}
